<?php

namespace app\user\controller;
use app\common\controller\UserBase;

class Index extends UserBase
{
    protected $noLogin = ['login', 'captcha', 'home'];
    protected $noAuth = ['index', 'uploadImage', 'uploadFile', 'uploadVideo', 'icon', 'logout'];

    protected function _initialize()
    {
        parent::_initialize();
        
    }
    //系统首页
    public function index()
    {
        !config('website_status') && die(config('colse_explain'));
        $config = cache('db_config_data');
        if (!$config) {
            $config = [];
            foreach (model('config')->select() as $v) {
                $config[$v['group']][$v['name']] = $v['value'];
            }
            cache('db_config_data', $config);
        }
        config($config);
        return $this->fetch('index');
    }
    //默认首页
    public function home()
    {
        //本月
        $beginToday = mktime(0,0,0,date('m'),date('d'),date('Y'));
        $endToday = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
        //今年
        $yearstart = strtotime(date('Y-1-1 00:00:00'));
        //基本数据
        $data['mshouru'] = number_format(model('finance')->where("type='1' and datetime >='".$beginToday."' and datetime <='".$endToday."'")->sum('price'));
        $data['mzhichu'] = number_format(model('finance')->where("type='2' and datetime >='".$beginToday."' and datetime <='".$endToday."'")->sum('price'));
        $data['yshouru'] = number_format(model('finance')->where("type='1' and datetime >='".$yearstart."' and datetime <='".$endToday."'")->sum('price'));
        $data['yzhichu'] = number_format(model('finance')->where("type='2' and datetime >='".$yearstart."' and datetime <='".$endToday."'")->sum('price'));
        
        //订单金额表
        $start_time = mktime(0,0,0,date('m',strtotime('-30 days')),date('d',strtotime('-30 days')),date('Y',strtotime('-30 days')));
        $end_time = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
        $now_j = (($end_time-$start_time)/86400);
        $array = array();
        $value = array();
        $num = '0';
        for($i=0;$i<$now_j;$i++){
            $array[] = $dtrq = date('d',$start_time+$i*86400); //每隔一天赋值给数组
            $day_begin = $start_time+$i*86400;
            $day_end = ($start_time+$i*86400)+86399;
            $money[] = $nums = model('finance')->where("datetime >='".$day_begin."' and datetime <= '".$day_end."'")->sum('price');
            $dingdan[] = $nums = model('finance')->where("datetime >='".$day_begin."' and datetime <= '".$day_end."'")->count();
            $num = $num + $nums;
        }
        return $this->fetch('home',[
            'data' => $data,
            'array' => $array,
            'money' => $money,
            'dingdan' => $dingdan,
            'num'=>$num
        ]);
    }
    //学校设置
    public function shop()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $param['update_time'] = time();
            $verify = input('_verify', true);
            if ($this->update('shop', $param, $verify) === true) {
                $this->success('设置成功', url('user/index/shop'));
            } else {
                $this->error($this->errorMsg);
            }
        }else{
            $data = model('shop')->get(session('user_auth.shop_id'));
            if(!$data){
                $this->error('暂未识别到学校，请先绑定学校！'); 
            }
        }        
        return $this->fetch('shop',[
            'data' => $data,
        ]);
    }
    //修改个人信息
    public function info()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $param['id'] = session('user_auth.user_id');
            $result = $this->validate($param, 'user');
            if ($result !== true) {
                $this->error($result);
            }
            $verify = input('_verify', true);
            if ($this->update('user', $param, $verify) === true) {
                insert_user_log('修改个人信息');
                // 保存状态
                $auth = [
                    'user_id' => session('user_auth.user_id'),
                    'shop_id' => session('user_auth.shop_id'),
                    'username' => session('user_auth.username'),
                    'realname' => $param['realname'],
                ];
                session('user_auth', $auth);
                session('user_auth_sign', data_auth_sign($auth));
                $this->success('修改成功', url('user/index/info'));
            } else {
                $this->error($this->errorMsg);
            }
        }
        return $this->fetch('info', [
            'data' => model('user')->with('userAuthGroupAccess')->where('id', session('user_auth.user_id'))->find(),
            'userAuthGroup' => model('userAuthGroup')->where('status', 1)->select(),]);
    }
    public function login()
    {
        is_user_login() && $this->redirect('user/index/index'); // 登录直接跳转
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $result = $this->validate($param, 'login');
            if ($result !== true) {
                $this->error($result);
            }
            $admin = model('user')->where([
                'username' => $param['username'],
                'password' => md5($param['password'])
            ])->find();
            if ($admin) {
                $admin['status'] != 1 && $this->error('账号已禁用');
                $admin['sid'] == 0 && $this->error('未绑定学校，请联系管理员');
                // 保存状态
                $auth = [
                    'user_id' => $admin['id'],
                    'username' => $admin['username'],
                    'shop_id' => $admin['sid'],
                    'realname' => $admin['realname'],
                ];
                session('user_auth', $auth);
                session('user_auth_sign', data_auth_sign($auth));
                // 更新信息
                model('user')->save([
                    'last_login_time' => time(),
                    'last_login_ip'   => $this->request->ip(),
                    'login_count'     => $admin['login_count'] + 1,
                ], ['id' => $admin['id']]);
                insert_user_log('登录了后台系统');
                $this->success('登录成功', url('user/index/index'));
            } else {
                $this->error('账号或密码错误');
            }
        }
        return $this->fetch('login');
    }

    public function captcha()
    {
        $config = [
            // 验证码字符集合
            'codeSet'  => '1234567890',
            // 验证码字体大小(px)
            'fontSize' => 16,
            // 是否画混淆曲线
            'useCurve' => false,
            // 验证码图片高度
            'imageH'   => 42,
            // 验证码图片宽度
            'imageW'   => 135,
            // 验证码位数
            'length'   => 4,
            // 验证成功后是否重置
            'reset'    => true,
        ];
        return captcha('', $config);
    }

    public function uploadImage()
    {
        try {
            $file = $this->request->file('file');
            $qiniuConfig = include(__DIR__ ."/../../setting.php");
            //判断上传位置
            if($qiniuConfig['qiniu']['type']=='1'){//七牛
                //$file = $this->request->file('file');
                // 要上传图片的本地路径
                $filePath = $file->getRealPath();
                $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
                //$size = $this->sizecount(filesize($filePath));
                // 上传到七牛后保存的文件名
                $key = date('Y').'/'.date('md').'/'.date('YmdHis').rand(0,9999).substr(md5($file->getRealPath()),0,5). '.' . $ext;
                include APP_PATH . '/../vendor/qiniu/autoload.php';
                // 需要填写你的 Access Key 和 Secret Key
                $accessKey = $qiniuConfig['qiniu']['upak'];
                $secretKey = $qiniuConfig['qiniu']['upsk'];
                // 构建鉴权对象
                $auth = new Auth($accessKey, $secretKey);
                // 要上传的空间
                $bucket = $qiniuConfig['qiniu']['upbucket'];
                $domain = $qiniuConfig['qiniu']['updomain'];
                $token = $auth->uploadToken($bucket);
                // 初始化 UploadManager 对象并进行文件的上传
                $uploadMgr = new UploadManager();
                // 调用 UploadManager 的 putFile 方法进行文件的上传
                list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
                if ($err !== null) {
                    return ["err"=>1,"msg"=>$err,"data"=>""];
                } else {
                    //返回图片的完整URL
                    return ['code' => 1, 'url' => $domain.$ret['key']];
                }
            }else{//默认本地
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'image');
                if ($info) {//               
                    $upload_image = unserialize(config('upload_image'));
                    if ($upload_image['is_thumb'] == 1 || $upload_image['is_water'] == 1 || $upload_image['is_text'] == 1) {
                        $object_image = \think\Image::open($info->getPathName());
                        // 图片压缩
                        if ($upload_image['is_thumb'] == 1) { 
                            $object_image->thumb($upload_image['max_width'], $upload_image['max_height']);
                        }
                        // 图片水印
                        if ($upload_image['is_water'] == 1) {
                            $object_image->water(ROOT_PATH . str_replace('/', '\\', trim($upload_image['water_source'], '/')), $upload_image['water_locate'], $upload_image['water_alpha']);
                        }
                        // 文本水印
                        if ($upload_image['is_text'] == 1) {
                            $font = !empty($upload_image['text_font']) ? str_replace('/', '\\', trim($upload_image['text_font'], '/')) : 'vendor\topthink\think-captcha\assets\zhttfs\1.ttf';
                            $object_image->text($upload_image['text'], ROOT_PATH . $font, $upload_image['text_size'], $upload_image['text_color'], $upload_image['text_locate'], $upload_image['text_offset'], $upload_image['text_angle']);
                        }
                        $object_image->save($info->getPathName());
                    }
                    return ['code' => 1, 'url' => '/uploads/image/' . str_replace('\\', '/', $info->getSaveName())];
                }else {
                    return ['code' => 0, 'msg' => $file->getError()];
                }
            }
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => $e->getMessage()];
        }
    }

    public function uploadFile()
    {
        try {
            $file = $this->request->file('file');
            $qiniuConfig = include(__DIR__ ."/../../setting.php");
            //判断上传位置
            if($qiniuConfig['qiniu']['type']=='1'){//七牛
                //$file = $this->request->file('file');
                // 要上传图片的本地路径
                $filePath = $file->getRealPath();
                $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
                //$size = $this->sizecount(filesize($filePath));
                // 上传到七牛后保存的文件名
                $key = date('Y').'/'.date('md').'/'.date('YmdHis').rand(0,9999).substr(md5($file->getRealPath()),0,5). '.' . $ext;
                include APP_PATH . '/../vendor/qiniu/autoload.php';
                // 需要填写你的 Access Key 和 Secret Key
                $accessKey = $qiniuConfig['qiniu']['upak'];
                $secretKey = $qiniuConfig['qiniu']['upsk'];
                // 构建鉴权对象
                $auth = new Auth($accessKey, $secretKey);
                // 要上传的空间
                $bucket = $qiniuConfig['qiniu']['upbucket'];
                $domain = $qiniuConfig['qiniu']['updomain'];
                $token = $auth->uploadToken($bucket);
                // 初始化 UploadManager 对象并进行文件的上传
                $uploadMgr = new UploadManager();
                // 调用 UploadManager 的 putFile 方法进行文件的上传
                list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
                if ($err !== null) {
                    return ["err"=>1,"msg"=>$err,"data"=>""];
                } else {
                    //返回图片的完整URL
                    return ['code' => 1, 'url' => $domain.$ret['key']];
                }
            }else{//默认本地
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'file');
                if ($info) {
                    return ['code' => 1, 'url' => '/uploads/file/' . str_replace('\\', '/', $info->getSaveName())];
                } else {
                    return ['code' => 0, 'msg' => $file->getError()];
                }
            }
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => $e->getMessage()];
        }
    }

    public function uploadVideo()
    {
        try {
            $file = $this->request->file('file');
            $qiniuConfig = include(__DIR__ ."/../../setting.php");
            //判断上传位置
            if($qiniuConfig['qiniu']['type']=='1'){//七牛
                //$file = $this->request->file('file');
                // 要上传图片的本地路径
                $filePath = $file->getRealPath();
                $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
                //$size = $this->sizecount(filesize($filePath));
                // 上传到七牛后保存的文件名
                $key = date('Y').'/'.date('md').'/'.date('YmdHis').rand(0,9999).substr(md5($file->getRealPath()),0,5). '.' . $ext;
                include APP_PATH . '/../vendor/qiniu/autoload.php';
                // 需要填写你的 Access Key 和 Secret Key
                $accessKey = $qiniuConfig['qiniu']['upak'];
                $secretKey = $qiniuConfig['qiniu']['upsk'];
                // 构建鉴权对象
                $auth = new Auth($accessKey, $secretKey);
                // 要上传的空间
                $bucket = $qiniuConfig['qiniu']['upbucket'];
                $domain = $qiniuConfig['qiniu']['updomain'];
                $token = $auth->uploadToken($bucket);
                // 初始化 UploadManager 对象并进行文件的上传
                $uploadMgr = new UploadManager();
                // 调用 UploadManager 的 putFile 方法进行文件的上传
                list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
                if ($err !== null) {
                    return ["err"=>1,"msg"=>$err,"data"=>""];
                } else {
                    //返回图片的完整URL
                    return ['code' => 1, 'url' => $domain.$ret['key']];
                }
            }else{//默认本地
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'video');
                if ($info) {
                    return ['code' => 1, 'url' => '/uploads/video/' . str_replace('\\', '/', $info->getSaveName())];
                } else {
                    return ['code' => 0, 'msg' => $file->getError()];
                }
            }
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => $e->getMessage()];
        }
    }

    public function icon()
    {
        return $this->fetch();
    }

    // 修改密码
    public function editPassword()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            // 验证条件
            empty($param['password']) && $this->error('请输入旧密码');
            empty($param['new_password']) && $this->error('请输入新密码');
            empty($param['rep_password']) && $this->error('请输入确认密码');
            !check_password($param['new_password'], 6, 16) && $this->error('请输入6-16位的密码');
            $param['new_password'] != $param['rep_password'] && $this->error('两次密码不一致');
            $admin = model('user')->where('id', session('user_auth.user_id'))->find();
            $admin['password'] != md5($param['password']) && $this->error('旧密码错误');
            $data = ['id' => session('user_auth.user_id'), 'password' => $param['new_password']];
            if ($this->update('user', $data, false) === true) {
                insert_user_log('修改了登录密码');
                $this->success('更新成功', url('user/index/index'));
            } else {
                $this->error($this->errorMsg);
            }
        }
        return $this->fetch('editPassword');
    }

    // 退出登录
    public function logout()
    {
        insert_user_log('退出了后台系统');
        session('user_auth', null);
        session('user_auth_sign', null);
        $this->redirect('user/index/login');
    }

    // 清除缓存
    public function clear()
    {
        clear_cache();
        insert_user_log('清除了系统缓存');
        $this->success('清除成功');
    }
}
